<?php

declare(strict_types=1);

namespace App\Job;

use App\Event\UserChatEvent;
use App\Helpers\ConfigUtil;
use App\Model\Message;
use App\Model\User;
use App\Model\UserChat;
use App\Model\UserMsgLog;
use App\Model\UserProfile;
use Hyperf\AsyncQueue\Job;
use Psr\EventDispatcher\EventDispatcherInterface;
use App\Amqp\Producer\ImMsgProducer;
use App\Helpers\Helper;
use App\Helpers\ImUtil;
use App\Helpers\RedisUtil;
use App\Model\GiftBatchLog;
use App\Model\Service\GiftService;
use App\Model\Setting\SettingOfficialChat;

/**
 * 聊天消息实时路由
 */
class ProcessImCallback extends Job
{
    public $callbackInfo;

    public function __construct($callbackInfo = [])
    {
        $this->callbackInfo = $callbackInfo;
    }

    public function handle()
    {
        $fromImAccount = $this->callbackInfo['fromUserId'];
        $toImAccount = $this->callbackInfo['toUserId'];
        $userIds = User::getUserIdByIm([$fromImAccount, $toImAccount]);
        $userId = $userIds[$fromImAccount];
        $chatUserId = $userIds[$toImAccount];
        if (strlen($toImAccount) < 15 || strlen($fromImAccount) < 15) {
            log_info(__CLASS__ . "==Error==From:{$fromImAccount}==To:{$toImAccount}");
            return;
        }
        log_info(__CLASS__ . "==From:{$fromImAccount}==To:{$toImAccount}");
        //官方账号
        // $officialUids = User::getOfficialIds();

        //聊天记录
//        $info = [
//            'from_account' => $fromImAccount,
//            'to_account' => $toImAccount,
//            'msg_detail' => json_encode($this->callbackInfo),
//            'from_userid' => $userId,
//            'to_userid' => $chatUserId,
//            'msg_type' => $this->callbackInfo['objectName'],
//            'official' => 0,
//        ];
//        $msgInfo = UserMsgLog::create($info);

        //聊天数量更新
        $userChat = UserChat::updateMsgNum($userId, $chatUserId, 1);

        //消息记录进入队列
        // $this->pushAmqp($info, $userChat, $officialUids, $userId, $chatUserId);

        //小助手消息回复
        $content = $this->callbackInfo['content']['content'] ?? '';
        $this->officialFeedBack($fromImAccount, $toImAccount, $content, $userId);

        //每日任务检测
        make(EventDispatcherInterface::class)->dispatch(new UserChatEvent($userId, $chatUserId, $userChat));
    }

    /**
     * 推送到amqp队列中，转发给客服系统
     */
    function pushAmqp($msgObj = [], $userChat = null, $officialUids = [], $userId, $chatUserId)
    {
        $sendFrom = in_array($userId, $officialUids);
        $sendTo = in_array($chatUserId, $officialUids);
        if (($sendTo && $sendFrom) || (!$sendFrom && !$sendTo)) return;
        $msgObj['send'] = $sendFrom ? 1 : 0;
        $msgObj['msg_time'] = date('Y-m-d H:i:s');
        $msgObj['msgUID'] = $this->callbackInfo['msgUID'];
        Helper::produceAmqp(new ImMsgProducer(json_encode($msgObj)));
        log_info(__CLASS__ . "==pushAmqp==UserChat:{$userChat->id}==UserId:{$userId}==ChatUserId:{$chatUserId}");
        return;
    }

    /**
     * 小助手消息回复
     */
    function officialFeedBack($fromImAccount = '', $toImAccount = '', $content = '', $fromUserId = 0)
    {
        if (!$content) return false;
        $officialAccount = env('IM_ACCOUNT_KEFU', '');
        $officialAccount2 = env('IM_ACCOUNT_KEFU2', '');
        if (!in_array($toImAccount, [$officialAccount, $officialAccount2])) return false;
        $key = "Official_feedback_{$fromImAccount}";
        $lockTime = check_dev_env() ? 30 : env('OFFICIAL_CHAT_OFF_TIME', 3600);
        if ($answer = SettingOfficialChat::getAnswerByKey($content)) {
            return ImUtil::sendTextMsg($fromImAccount, $answer, $officialAccount);
        } else {
            if (RedisUtil::concurrentLock($key, $lockTime)) return false;
        }
        switch ($toImAccount) {
            case $officialAccount2:
                $msg = '你好，我是客服，很高兴为你服务，请你描述想要咨询的相关问题。';
                break;
            case $officialAccount:
                $msg = '你好，我是小助手，很高兴为你服务，请你描述想要咨询的相关问题。';
                break;
        }
        ImUtil::sendInfoTipMsg($fromImAccount, $msg, $toImAccount);
        // $kefu = config('busi.kefu_wechat');
        // $msg = '为了给您提供优质服务，我将尽快转接到人工客服为您服务，请您稍等~';
        //         $msg = '你好，小助手在，请问有什么可以帮您？
        // 1、平台屏蔽了联系方式和地址吗？
        // 2、音视频中说联系方式时平台卡顿？
        // 3、聊天、语音/视频需要收费吗？
        // 4、平台需要缴纳保证金吗？
        // 5、投诉
        // 如遇以上问题请直接回复数字获取帮助。';
        // if ($answer = SettingOfficialChat::getAnswerByKey($content)) {
        // $profile = UserProfile::getProfile($fromUserId);
        // if ($profile->gender == 0) {
        //     $msg = '我这边会发一份平台操作手册和资料你，你方便添加一下客服微信' . $kefu . '吗？';
        // }
        //     $msg = $answer;
        // }
        // ImUtil::sendTextMsg($fromImAccount, $msg, $officialAccount);
        return true;
    }
}
